<?php

require_once('Zend/Db/Table/Row/Abstract.php');
require_once('Zend/Db/Table/Abstract.php');
require_once('Zend/Db/Table.php');
require_once('Zend/Db/Expr.php');

class Core_OAuth_Consumer extends Zend_Db_Table_Row_Abstract
{
	/**
	 * Private static reference to the table.
	 *
	 * @return Zend_Db_Table
	 */
	private static $table;

	/**
	 * Name of the class of the Zend_Db_Table_Abstract object.
	 *
	 * @var string
	 */
	protected $_tableClass = 'Zend_Db_Table';

	/**
	 * Select access method, for slightly more complex queries.
	 *
	 * @return Zend_Db_Table_Select
	 */
	public static function getTableInstance ()
	{
		if (empty(Core_OAuth_Consumer::$table))
		{
			Core_OAuth_Consumer::$table = new Zend_Db_Table('oauth_consumer');
			Core_OAuth_Consumer::$table->setRowClass('Core_OAuth_Consumer');
		}

		return Core_OAuth_Consumer::$table;
	}

	/**
	 * Factory Method. Spits out an object that's tied to the database.
	 *
	 * @return Core_OAuth_Consumer
	 */
	public static function factory ($id_or_key = null)
	{
		$table = Core_OAuth_Consumer::getTableInstance();
		$row = null;
		if (is_null($id_or_key))
		{
			// Create new
			$row = $table->createRow(array(), Zend_Db_Table_Abstract::DEFAULT_DB);
		}
		else if (is_string($id_or_key))
		{
			// Find by consumer key.
			$row = $table->fetchRow($table->select()->where('consumerKey=?', $id_or_key));
		}
		else if (is_int($id_or_key))
		{
			// Find by ID.
			$row = $table->fetchRow($table->select()->where('oauthConsumerId=?', $id_or_key));
		}

		return $row;
	}

	/**
	 * @inheritDoc
	 */
	protected function _doInsert ()
	{
		$this->created = new Zend_Db_Expr('NOW()');
		$this->updated = new Zend_Db_Expr('NOW()');

		parent::_doInsert();
	}

	/**
	 * @inheritDoc
	 */
	protected function _doUpdate ()
	{
		$this->updated = new Zend_Db_Expr('NOW()');

		parent::_doUpdate();
	}
}
